#!/usr/bin/env bash
# NOTE execute this file at by6pms project root

set -euo pipefail

basepath=$(cd `dirname $0`; pwd)

# ==============================================================================
# helper functions

. $basepath/lib.sh

# ==============================================================================
# Code

if [[ -f .env ]]; then
    . .env
fi

# ----------------
# collect static
python3 ./manage.py collectstatic

# -----------------
# setup databse

if yes_or_no "Do you want to setup database?"; then
    if mysql -u $BY6PMS_MYSQL_USER --password=$BY6PMS_MYSQL_PASSWORD "$BY6PMS_MYSQL_DATABASE_NAME" -e exit > /dev/null 2>&1; then
        # database exists
        if yes_or_no "Do you want to drop the database $BY6PMS_MYSQL_DATABASE_NAME and create a new one?"; then
            mysql -u $BY6PMS_MYSQL_USER --password=$BY6PMS_MYSQL_PASSWORD -e "drop database $BY6PMS_MYSQL_DATABASE_NAME; create database $BY6PMS_MYSQL_DATABASE_NAME CHARACTER SET utf8;"
        fi
    else
        echo "[*] Create new database '$BY6PMS_MYSQL_DATABASE_NAME'"
        mysql -u $BY6PMS_MYSQL_USER --password=$BY6PMS_MYSQL_PASSWORD -e "create database $BY6PMS_MYSQL_DATABASE_NAME CHARACTER SET utf8;"
    fi

    python3 ./manage.py migrate
    python3 ./manage.py loaddata initial.yaml
    
    if yes_or_no "Do you want to create super user from environment variables (see .env_example)?"; then
        python3 ./manage.py createsuperuser --no-input
    fi
fi

# -----------------
# setup nginx

if yes_or_no "Do you want to setup nginx?"; then
    nginx_conf_file=/etc/nginx/conf.d/by6pms.conf
    nginx_conf_backup_file="${nginx_conf_file}.bak"
    if [[ -f $nginx_conf_backup_file ]]; then
        if yes_or_no "Delete file $nginx_conf_backup_file?"; then
            rm $nginx_conf_backup_file
        else
            echo "Please manually move $nginx_conf_backup_file to elsewhere!"
            exit 1
        fi
    fi

    if [[ -f $nginx_conf_file ]]; then
        mv $nginx_conf_file $nginx_conf_backup_file
    fi

    cp ./00_script/config/nginx.conf $nginx_conf_file
fi

# -----------------
# setup systemd services

if yes_or_no "Do you want to setup systemd service?"; then
    sh $basepath/setup_systemd_service.sh
fi

